import { defineStore } from "pinia"
import { ref, computed } from 'vue'
import { useUserInfoStore } from './user'
import { insertCartAPI,findNewCartListAPI,delCartAPI } from "@/api/cart"

export const useCartStore = defineStore('cart',() =>{
    const userStore = useUserInfoStore()
    const isLogin = computed(() => (userStore.userInfo as any).token)
    // 定义购物车列表初始状态
    const cartList = ref<any>([])
    // 定义 action 方法
    const addCart = async (goods:any) =>{
        const { skuId,count } = goods
        if(isLogin.value){
            await insertCartAPI({skuId,count})
            updateNewList()
        }else{
            // 添加购物车操作
            const item = cartList.value.find((item:any) =>goods.skuId === item.skuId)
            if(item){
                item.count++
            }else{
                cartList.value.push(goods)
            } 
        }
    }

     // 删除购物车
     const delCart = async (skuId:any) =>{
        if(isLogin.value){
            await delCartAPI([skuId])
            updateNewList()
        }else{
            const idx = cartList.value.findIndex((item:any) =>skuId === item.skuId)
            cartList.value.splice(idx,1)
        }
       }

       // 获取最新购物车的列表 封装
       const updateNewList = async () =>{
        const res:any = await findNewCartListAPI()
        cartList.value = res.result
       }

       // 清空购物车
       const clearCart = async () =>{
        cartList.value = []
       }

       // 单选功能
       const singleCheck = (skuId:any,selected:any) =>{
        const item = cartList.value.find((item:any) => item.skuId ===skuId)
        item.selected = selected
       }

       // 全选功能
       const allCheck = (selected:any) =>{
        console.log
        cartList.value.forEach((item:any) =>item.selected = selected)
       }

       // 计算属性
       // 计算总数量
       const allCount = computed(() => cartList.value.reduce((a:any,c:any) => a + c.count,0 ))
       // 计算总价格
       const allPrice = computed(() => cartList.value.reduce((a:any,c:any) => a + c.count * c.price,0))

       // reduce 第一个参数是一个回调函数，第二个参数是一个初始的默认值


       // 是否全选
       const isAll = computed(() =>cartList.value.every((item:any) => item.selected))

       // 已选择数量
       const selectedCount = computed(() => cartList.value.filter((item:any) => item.selected).reduce((a:any,c:any) => a + c.count,0 ))
       // 已选择价格
       const selectedPrice = computed(() => cartList.value.filter((item:any) => item.selected).reduce((a:any,c:any) => a + c.count * c.price,0 ))

    return{
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        singleCheck,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,
        clearCart,
        updateNewList
    }
},
{
    persist:true
})